package com.sdkj.fixed.asset.hc.controller;


import cn.hutool.core.date.DateUtil;
import com.sdkj.fixed.asset.api.hc.ReceiptInApi;
import com.sdkj.fixed.asset.api.hc.vo.in.ReceiptInGetPageParams;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptInExtend;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptInGetPage;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptInGetPageNew;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptMoveProductExtend;
import com.sdkj.fixed.asset.common.base.*;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.hc.service.ReceiptInService;
import com.sdkj.fixed.asset.hc.util.CacheUtil;
import com.sdkj.fixed.asset.hc.util.ExcelStyle;
import com.sdkj.fixed.asset.hc.util.ExcelUtils;
import com.sdkj.fixed.asset.pojo.hc.ReceiptIn;
import com.sdkj.fixed.asset.pojo.hc.group.AddReceiptIn;
import com.sdkj.fixed.asset.pojo.hc.group.DelReceiptIn;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 史晨星
 * @ClassName: ReceiptInController
 * @Description: 入库单
 * @date 2020年7月20日
 */
@Validated
@RestController()
public class ReceiptInController extends BaseController<ReceiptIn> implements ReceiptInApi {

    private static Logger log = LoggerFactory.getLogger(ReceiptInController.class);

    @Resource
    private HttpServletResponse response;

    @Resource
    private ReceiptInService service;

    @Resource
    private HttpServletRequest request;

    @Override
    public BaseService<ReceiptIn> getService() {
        return service;
    }

    @Resource
    private CacheUtil cacheUtil;

    /**
     * 新增
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo add(@Validated({AddReceiptIn.class}) ReceiptIn entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setCuser(userId);
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        entity.setCtime(DateUtil.now());
        entity.setOrgId(orgId);
        entity.setState(1);
        ReceiptIn receiptIn = service.add(entity);
        return BaseResultVo.success("success", receiptIn.getId());
    }

    /**
     * 修改
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo edit(@Validated ReceiptIn entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setOrgId(orgId);
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        ReceiptIn receiptIn = service.edit(entity, false);
        return BaseResultVo.success("success", receiptIn.getId());
    }

    /**
     * 查看
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo view(@Validated({DelReceiptIn.class}) ReceiptIn entity) throws Exception {
        ReceiptIn receiptIn = service.view(entity.getId());
        return BaseResultVo.success("success", receiptIn);
    }

    /**
     * 删除
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo del(@Validated ReceiptIn entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        ReceiptIn receiptIn = service.del(entity);
        return BaseResultVo.success("success", receiptIn.getId());
    }

    /**
     * 列表查询
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @ApiOperation(value = "列表查询", notes = "列表查询")
    public BaseResultVo getPages(@Validated PageParams<ReceiptInGetPageParams> params) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        params.getParams().setOrgId(orgId);
        params.getParams().setUserId(userId);
        List<ReceiptInGetPageNew> pageList = service.getPages(params);
        PageBean<ReceiptInGetPageNew> page = new PageBean<>(pageList);
        return BaseResultVo.success(page);
    }


    /**
     * 打印
     *
     * @param ids
     * @throws Exception
     */
    @Override
    public void print(String ids) throws Exception {
        List<ReceiptInExtend> extendss = service.print(ids);
        final String[] fileName = {"入库单卡片"};
        HSSFWorkbook wb = new HSSFWorkbook();
        extendss.stream().forEach(extend -> {
            String title = "";
            if (extend.getType() == 1) {
                title = "入库单卡片";
            } else {
                title = "盘盈入库单卡片";
                fileName[0] = title;
            }
            String sheetName = extend.getNumber();

            HSSFRow row = null;
            HSSFCell cell = null;
            int rownum = 0;
            // 建立新的sheet对象（excel的表单） 并设置sheet名字
            HSSFSheet sheet = wb.createSheet(sheetName);
            sheet.setDefaultColumnWidth(18);
            sheet.setColumnWidth(0, 256 * 6);
            sheet.setDefaultRowHeight((short) 512);

            // 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
            row = sheet.createRow(rownum++);
            row.setHeight((short) 1000);
            // 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
            cell = row.createCell(1);
            // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8));
            cell.setCellValue(title);
            cell.setCellStyle(ExcelStyle.styleTitle(wb));

            String[] row1 = {"入库单号：", extend.getNumber(), "", "入库仓库：", extend.getCategoryName(), "", "业务时间：", extend.getBussinessDate()};
            String[] row2 = {"供应商", extend.getProvider(), "", "经办人：", extend.getCuser(), "", "经办时间：", extend.getCtime()};
            String[] row3 = {"入库备注：", extend.getComment(), "", "", "", "", "", ""};
            String[] row4 = {};
            String[] row5 = {"物品编码", "物品名称", "商品编码", "规格型号", "单位", "入库数量", "入库单价", "入库金额"};
            List<String[]> rowList = new ArrayList<>();
            rowList.add(row1);
            rowList.add(row2);
            rowList.add(row3);
            rowList.add(row4);
            rowList.add(row5);

            for (String[] rows : rowList) {
                row = sheet.createRow(rownum++);
                for (int i = 0; i < rows.length; i++) {
                    cell = row.createCell(i + 1);
                    cell.setCellValue(rows[i]);
                    if (rownum == 4) {
                        cell.setCellStyle(ExcelStyle.styleCellName(wb));
                        row.setHeight((short) 700);
                    } else if (rownum == 6) {
                        cell.setCellStyle(ExcelStyle.styleCellName(wb));
                    } else if (rownum == 2) {
                        cell.setCellStyle(ExcelStyle.styleCellName(wb));
                    } else if (rownum == 3) {
                        cell.setCellStyle(ExcelStyle.styleCellName(wb));
                    } else if (rownum == 7) {
                        cell.setCellStyle(ExcelStyle.styleCellName(wb));
                    } else if (rownum == 5) {
                        cell.setCellStyle(ExcelStyle.styleCellName(wb));
                    } else {
                        cell.setCellStyle(ExcelStyle.styleCellName(wb));
                    }

                }
            }

            //合并单元格
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3));
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 5, 6));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 2, 3));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 5, 6));
            sheet.addMergedRegion(new CellRangeAddress(3, 3, 2, 8));
            //遍历数据
            int j = 1;
            for (ReceiptMoveProductExtend result : extend.getReceiptMoveProductList()) {
                row = sheet.createRow(rownum++);
                String[] cells = {result.getCode(), result.getName(), result.getBarCode(), result.getModel(), result.getUnit(), result.getNum().toString(), result.getPrice(), result.getTotalPrice()};
                for (int i = 0; i < cells.length; i++) {
                    cell = row.createCell(i + 1);
                    cell.setCellValue(cells[i]);
                    cell.setCellStyle(ExcelStyle.styleCellValue(wb));
                }
            }
        });


        // 输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName[0] + ".xlsx", "UTF-8"));    //filename =  文件名
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
    }

    /**
     * 导出
     *
     * @param number
     * @param companyId
     * @param type
     * @param categoryId
     * @param userId
     * @param response
     * @throws Exception
     */
    @Override
    public void export(Integer type, String number, String companyId, String categoryId, String userId, HttpServletResponse response) throws Exception {
        ReceiptInGetPageParams params = new ReceiptInGetPageParams();
        params.setType(type);
        params.setCategoryId(categoryId);
        params.setOrgId(companyId);
        params.setUserId(userId);
        params.setNumber(number);
        List<ReceiptInGetPage> pageList = service.export(params);
        String fileName = "";
        if (type == 1) {
            fileName = "耗材入库单";
        } else {
            fileName = "耗材盘盈入库单";
        }
        ExcelUtils.exportExcel(pageList, fileName, fileName, ReceiptInGetPage.class, fileName + TimeTool.getTimeDate14(), response);
    }
}

